using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Identity.AdminSecurityExtensions
{
    public class CustomAuthorizationPolicyProvider : DefaultAuthorizationPolicyProvider
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

        public CustomAuthorizationPolicyProvider(IOptions<AuthorizationOptions> options, IHttpContextAccessor httpContextAccessor)
            : base(options)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        public override async Task<AuthorizationPolicy?> GetPolicyAsync(string policyName)
        {
            // 检查策略名称是否以 "UserNavigation:" 开头
            if (policyName.StartsWith("UserNavigation:"))
            {
                var userNavigationName = policyName.Split(':')[1];

                // 从当前作用域解析服务
                var serviceProvider = _httpContextAccessor.HttpContext?.RequestServices;
                if (serviceProvider == null)
                {
                    throw new InvalidOperationException("Unable to resolve scoped services.");
                }

                var requirement = new UserNavigationRequirement(serviceProvider);

                // 动态创建策略
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .AddRequirements(requirement)
                    .Build();

                return await Task.FromResult(policy);
            }

            // 如果不是动态策略，调用基类逻辑
            return await base.GetPolicyAsync(policyName);
        }
    }
}